import 'package:flutter/material.dart';
import 'package:flutter_ui/flavors/app_config.dart';
import 'package:flutter_ui/pages/task_list_page.dart';
import 'package:flutter_ui/common/app_theme.dart';
import 'package:flutter_ui/pages/main_navigation.dart';
import 'package:flutter_ui/launcher/splash_page.dart';
import 'package:flutter_ui/pages/login_page.dart';
import 'package:flutter_ui/pages/ehr_webview_page.dart';
import 'package:flutter_ui/services/auth_service.dart';
import 'package:provider/provider.dart';

/// 创建一个 GlobalKey 用于管理 Navigator 的状态
/// 全局导航键，用于在任何地方导航
/// 特别是在HTTP服务中处理401错误时跳转到登录页面
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

/// 应用程序入口
void main({String flavor = 'home_doctor'}) async {
  // 确保Flutter绑定初始化
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化应用配置
  AppConfig.init(flavor: flavor);
  
  // 初始化认证服务
  final authService = AuthService();
  await authService.init();
  
  // 运行应用
  runApp(const MyApp());
}

/// 家庭医生应用入口
void mainHomeDoctorApp() async {
  main(flavor: 'home_doctor');
}

/// 移动医生查房应用入口
void mainMobileDoctorApp() async {
  main(flavor: 'mobile_doctor');
}

/// 移动医疗应用入口
void mainMobileMedicalApp() async {
  main(flavor: 'mobile_medical');
}

/// EHR应用入口
void mainEhrApp() async {
  main(flavor: 'ehr');
}

/// 应用程序根组件
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final appConfig = AppConfig.instance;
    
    return MultiProvider(
      providers: [
        // 提供认证服务
        ChangeNotifierProvider(create: (_) => AuthService()),
      ],
      child: MaterialApp(
        title: appConfig.appName,
        debugShowCheckedModeBanner: false,
        theme: AppTheme.lightTheme.copyWith(
          colorScheme: ColorScheme.light(
            primary: appConfig.primaryColor,
            secondary: appConfig.secondaryColor,
          ),
        ),
        // 设置启动页为初始页面
        home: const SplashPage(),
        // 设置全局导航键，用于在任何地方导航
        navigatorKey: navigatorKey,
        routes: {
          '/login': (context) => const LoginPage(),
          '/home': (context) => const MainNavigation(),
          '/tasks': (context) => const TaskListPage(),
          '/ehr': (context) => EhrWebViewPage(url: AppConfig.instance.ehrUrl ?? ''),
        },
      ),
    );
  }
}

